from Behavior import Behavior
import GameKeys, Scripts.Options as Options, Rasterizer as ras

# This script will only work once the vehicle is properly setup.
# Make sure the kart's config file is run before this script!
#
# Tire 1 = Front driver's tire
# Tire 2 = Front passenger's tire
# Tire 3 = Rear driver's tire
# Tire 4 = Rear passenger's tire

class Player(Behavior):
	"""Behavior Based on vehicle physics constraints"""
	
	def __init__(self, cont):
		# Load the key dictionary
		self.keyDict = {}
		
		conf = open("keys.conf")
		
		for line in conf:
			key = line.split('=')
			self.keyDict[key[0]] = getattr(GameKeys, key[1].strip())
			
		conf.close()
		
		# Run the base __init__
		
		# Factors for analog input
		self.factors = {
					'Gas':1,
					'Reverse':1,
					'Brake':1,
					'EBrake':1,
					'Left':0,
					'Right':0,
					}
					
		Behavior.__init__(self, cont)
	
	def CheckInputs(self, keyboard, mouse, joystick):
		keyList = keyboard.events
		
		inputs = []
		
		# Reset the factors
		
		if keyList and keyboard:
			for key in keyList:
				if key[1] == 1 or 2: # Pressed or holding
					for input in self.keyDict: # Loop over the dict keys and see if one matches
						if key[0] == self.keyDict[input]:
							inputs.append(input)
							self.factors[input] = 1
			
		if Options.GetValue('UseMouseTurn'):
			# Setup the mouse if it hasn't been yet
			if not hasattr(self, "mouseCenter"):
				# We'll only go half way to the max window size
				self.mouseCenter = ras.getWindowWidth()*0.5
				self.mouseMin = ras.getWindowWidth()*0.25
				self.mouseMax = ras.getWindowWidth()*0.75
				ras.setMousePosition(ras.getWindowWidth()/2, ras.getWindowHeight()/2)
				ras.showMouse(1)
			else:
				if mouse.position[0] > self.mouseCenter:
					inputs.append('Right')
					if mouse.position[0] > self.mouseMax:
						self.factors['Right'] = 1
					else:
						self.factors['Right'] = mouse.position[0] / float(self.mouseMax)
				elif mouse.position[0] < self.mouseCenter:
					inputs.append('Left')
					if mouse.position[0] < self.mouseMin:
						self.factors['Left'] = 1
					else:
						self.factors['Left'] = abs(self.mouseCenter- mouse.position[0])/abs(self.mouseCenter - self.mouseMin)
				else:
					self.factors['Left'] = self.factors['Right'] = 0
						
				
			
		return inputs
	
	def CheckCollisions(self, collision):
		hitob = collision.hitObject
		
		if hitob.name.startswith("OBCheckpoint") and hitob not in self.cps:
			self.cps.append(collision.hitObject)
			
			if len(self.cps) == len(self.checkpoints):
				self.laps += 1
				self.cps = []
				
			# Update GameLogic too
			import GameLogic
			GameLogic.laps = self.laps
			
			if GameLogic.laps == GameLogic.maxlaps:
				GameLogic.sendMessage('victory')
				
	def main(self):
		own = self.cont.owner
		
		# Sensors
		keyboard	= self.cont.sensors["Keyboard"]
		mouse		= self.cont.sensors["Mouse"]
		joystick	= self.cont.sensors["Joystick"]
		collision	= self.cont.sensors["Collision"]
		
		# Parse the collisions
		if collision.positive:
			self.CheckCollisions(collision)
		
		# Parse one keyboard sensor for inputs
		inputs = self.CheckInputs(keyboard, mouse, joystick)
		
		gas		= ('Gas' in inputs)
		reverse	= ('Reverse' in inputs)
		brake	= ('Brake' in inputs)
		ebrake	= ('EBrake' in inputs)
		left	= ('Left' in inputs)
		right	= ('Right' in inputs)
		reset	= ('Reset' in inputs)
		
		if reset:
			self.ResetPosition()
		
		# Analog input can now be decided here
		
		self.Brake(brake, 1)
		
		self.Turn((left or right), (self.factors['Left'] if left else -self.factors['Right']))
		
		self.Move((gas or reverse), (self.factors['Gas'] if gas else -self.factors['Gas']))
						
		self.PlayActions(gas, reverse, brake, ebrake, left, right)
			
		
		